package top.lionkliu.servlet;

import lombok.SneakyThrows;
import top.lionkliu.entity.User;
import top.lionkliu.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet({"/user/add", "/user/edit", "/user/list", "/user/delete"})
public class UserServlet extends HttpServlet {
    private UserServiceImpl userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String servletPath = request.getServletPath();
        switch (servletPath) {
            case "/user/list":
                doList(request, response);
                break;
            case "/user/add":
                doAdd(request, response);
                break;
            case "/user/edit":
                doEdit(request, response);
                break;
            case "/user/delete":
                doDel(request, response);
                break;

        }
    }

    @SneakyThrows
    private void doList(HttpServletRequest request, HttpServletResponse response) {
        List<User> users = userService.selectAll();
        request.getSession().setAttribute("users", users);
        request.getRequestDispatcher("/admin/userManage.jsp").forward(request, response);
    }

    @SneakyThrows
    private void doDel(HttpServletRequest request, HttpServletResponse response) {
        int id = Integer.parseInt(request.getParameter("id"));
        userService.delete(id);
        response.sendRedirect(request.getContextPath() + "/user/list");
    }


    @SneakyThrows
    private void doEdit(HttpServletRequest request, HttpServletResponse response) {
        String userId = (String) request.getSession().getAttribute("userId");
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String pwd = request.getParameter("pwd");
        String img = request.getParameter("img");
        String identity = request.getParameter("identity");

        userService.updateUserInfo(new User(userId, name, pwd, email,identity,img));
        response.sendRedirect(request.getContextPath() + "/user/list");
    }

    @SneakyThrows
    private void doAdd(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String pwd = request.getParameter("pwd");
        userService.register(new User(name,email,pwd));
        response.sendRedirect(request.getContextPath() + "/user/list");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
